<template>
  <div class="main">
    <h2 class="main-title" v-if="type==1">添加商品</h2>
    <h2 class="main-title" v-if="type==2">编辑商品</h2>
    <div class="main-contain">
      <div class="content-wrapper">
        <el-row>
          <el-col :span="24">
            <el-form ref="goodsForm" :model="goodsForm" :label-width="formLableWidth" :rules="goodsRules">
              <el-form-item label="请选择商品" v-if="type==1">
                <template slot-scope="scope">
                  <div class="flex-box">
                     <el-select
                      class="db"
                      v-model="goodsForm.productName"
                      filterable
                      remote
                      placeholder="请输入商品名称或编号"
                      :remote-method="remoteProduct"
                      @focus="getProductList"
                      :disabled="type==3">
                      <el-option
                        v-for="(item, index) in productListData"
                        :key="index"
                        :label="item.name"
                        :value="item.productNo">
                      </el-option>
                    </el-select>
                    <el-button type="primary" @click="addProduct()">添加</el-button>
                    </div>
                </template>
              </el-form-item>
              <el-form-item label="SPU" v-if="type!=1">{{findCommodity.commodityNo}}</el-form-item>
              <el-form-item label="商品名称" prop="title">
                <el-input v-model="goodsForm.title" maxlength="20" placeholder="请输入商品名称或编号" :disabled="type==3"></el-input>备注：5-20个汉字
              </el-form-item>
              <el-form-item label="商品分类" prop="categoryId">
                <el-select  class="filter-item" placeholder="商品分类" v-model="goodsForm.categoryId" clearable :disabled="type==3">
                  <el-option v-for="(item,index) in CategoryData"
                    :key="index"
                    :label="item.categoryName"
                    :value="item.categoryId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="售卖规格">
                <div class="flex-box">
                  <el-input v-model="goodsForm.attribute" maxlength="2" placeholder="请输入规格，1-2个汉字" :disabled="type==3"></el-input>
                  <el-button type="primary" @click="addAttribute()" :disabled="type==3">添加</el-button>
                </div>
                <el-table :data="attributeData" stripe border v-loading="$store.state.loading">
                  <el-table-column label="规格" align="center" >
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.attributeName" :disabled="type==3"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="零售价" align="center">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.sellPrice" type="number" :disabled="type==3"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="摆放位置" align="center">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.position" :disabled="type==3"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="" label="操作" align="center">
                    <template slot-scope="scope">
                      <el-button type="text" size="mini" @click="del(scope.$index, attributeData)" :disabled="type==3">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
              <el-form-item label="商品主图">
                <div class="uploader-wrapper">
                  <el-upload
                    multiple
                    :limit="4"
                    :action="'http://api.teayk.com/sys/sysUtils/uploadFile'"
                    list-type="picture-card"
                    :file-list="imgList"
                    :before-upload="beforeUpload"
                    :on-success="uploadSuccess"
                    :on-preview="preView"
                    :on-remove="removeFile"
                    :on-exceed="overLimit"
                    :disabled="type==3">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  尺寸：750*750
                </div>
              </el-form-item>
              <el-form-item label="添加时间" v-if="type!=1">{{creatTime}}</el-form-item>
              <el-form-item label="操作记录" v-if="type==3">
                <p v-for="(item, index) in this.findCommodity.operateRecord" :key="index">{{item.operateTime}} , {{item.operater}} <span v-if="item.operateType === 1">创建</span> <span v-else>修改资料</span>。</p>
              </el-form-item>
              <el-form-item v-if="type !== 3">
                <el-button type="primary" @click="save('goodsForm')" v-loading="isLoading">保存</el-button>
                <el-button type="default" @click="cancel">取消</el-button>
              </el-form-item>
              <el-form-item v-if="type == 3">
                <el-button type="primary" @click="goback">返回</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </div>
     <!-- 图片预览 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl">
    </el-dialog>
  </div>
</template>

<script>
import { goodsRules } from '@/utils/rules'
import { formatDate } from '@/utils/date.js'
export default {
  data () {
    return {
      type: this.$route.query.type, // 1--添加 2-编辑 3-详情
      commodityId: this.$route.query.commodityId,
      goodsRules: goodsRules,
      bannerId: this.$route.query.bannerId || '',
      formLableWidth: '120px',
      goodsForm: {
        title: '',
        categoryId: '',
        productName: ''
      },
      operateTypeData: [{
        value: '1',
        label: '创建'
      }, {
        value: '2',
        label: '修改资料'
      }],
      creatTime: '', // 创建时间
      imgUrlList: [], // 商品主图
      imgList: [],
      dialogVisible: false,
      dialogImageUrl: '',
      productListData: [], // 商品列表
      findCommodity: [], // c查找商品
      CategoryData: [], // 商品分类
      attributeData: [], // 规格
      isLoading: false
    }
  },
  mounted () {
    this.categroyList()
    this.getProductList()
    if (this.type === 2 || this.type === 3) {
      this.getData()
    }
  },
  methods: {
    // 获取列表数据
    getData () {
      this.$http.post(this.$api + '/commodity/findCommodityInfoById', {
        commodityId: this.commodityId
      }).then(res => {
        if (res.responseCode === '0000') {
          this.findCommodity = res.data
          this.goodsForm.title = this.findCommodity.commodityName
          this.goodsForm.categoryId = this.findCommodity.categoryId
          if (this.findCommodity.commodityCover) {
            this.findCommodity.commodityCover.split(',').forEach(item => {
              this.imgUrlList.push(item)
              this.imgList.push({
                url: item
              })
            })
          }
          if (this.findCommodity.sellAttributesList) {
            this.findCommodity.sellAttributesList.forEach(item => {
              let sellAttributes = {}
              sellAttributes.attributeName = item.attributeName
              sellAttributes.sellPrice = item.sellPrice
              sellAttributes.position = item.position
              this.attributeData.push(sellAttributes)
            })
          }
          this.creatTime = formatDate(new Date(this.findCommodity.createTime), 'yyyy-MM-dd hh:mm:ss')
        } else {
          this.$message.error({
            duration: this.$store.state.duration,
            message: res.responseMsg
          })
        }
      }).catch(() => {
        this.$message.error({
          message: '请求超时！'
        })
      })
    },
    // 添加商品
    addProduct () {
      if (this.goodsForm.productName) {
        this.$http.post('http://api.teayk.com/commodity/product/findProductByProductNoAndProductName', {
          'productNameAndNum': this.goodsForm.productName
        }).then(res => {
          if (res.responseCode === '0000') {
            this.imgUrlList = []
            this.imgList = []
            this.goodsForm.title = res.data[0].name
            this.goodsForm.categoryId = res.data[0].categoryId
            if (res.data[0].productCover) {
              res.data[0].productCover.split(',').forEach(item => {
                this.imgUrlList.push(item)
                this.imgList.push({
                  url: item
                })
              })
            }
            this.goodsForm.productName = ''
          } else {
            this.$message.error({
              duration: this.$store.state.duration,
              message: res.responseMsg
            })
          }
        })
      } else {
        this.$message.error({
          duration: this.$store.state.duration,
          message: '请选择商品'
        })
      }
    },
    // 保存
    save (formName) {
      if (!this.isLoading) {
        this.$refs[formName].validate((valid) => {
          if (valid && this.imageUrl !== '' && this.attributeData.length) {
            let addoredit = ''
            if (this.type === 1) {
              addoredit = '添加'
            } else {
              addoredit = '编辑'
            }
            this.$confirm('确认' + addoredit + '商品？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.isLoading = true
              this.$http.post(this.$api + '/commodity/addOrUpdateCommodity', {
                commodityId: this.commodityId || '',
                commodityName: this.goodsForm.title,
                categoryId: this.goodsForm.categoryId,
                commoditySellAttribute: this.attributeData,
                commodityCover: this.imgUrlList.toString() || '' // 商品主图
              }).then(res => {
                if (res.responseCode === '0000') {
                  this.$message({
                    type: 'success',
                    message: res.responseMsg,
                    onClose: () => {
                      this.$router.push({
                        path: '/goods/index',
                        query: {
                          pg: this.$route.query.pg,
                          size: this.$route.query.size
                        }
                      })
                    }
                  })
                  setTimeout(() => {
                    this.isLoading = false
                  }, 3000)
                } else {
                  this.$message.error({
                    message: res.responseMsg
                  })
                }
              }).catch(err => {
                console.error(err)
              })
            }).catch(() => {
              this.$message({
                duration: this.$store.state.duration,
                type: 'info',
                message: '已取消'
              })
            })
          } else {
            this.$message.error({
              duration: this.$store.state.duration,
              message: '请填写完整信息'
            })
          }
        })
      }
    },
    // 商品列表
    getProductList () {
      return new Promise((resolve) => {
        let params = {
          'productNameAndNum': ''
        }
        this.$http.post('http://api.teayk.com/commodity/product/findProductByProductNoAndProductName', params).then(res => {
          if (res.responseCode === '0000') {
            this.productListData = res.data
            return resolve(this.productListData)
          } else {
            this.$message({
              duration: this.$store.state.duration,
              message: res.responseMsg,
              type: 'error'
            })
          }
        })
      })
    },
    // 远程搜索
    remoteProduct (query) {
      if (query !== '') {
        this.loading = true
        this.$http.post('http://api.teayk.com/commodity/product/findProductByProductNoAndProductName', {
          'productNameAndNum': query || ''
        }).then(res => {
          if (res.responseCode === '0000') {
            this.productListData = res.data
          } else {
            this.$message.error({
              message: res.responseMsg
            })
          }
        })
        this.loading = false
      } else {
        this.productListData = []
      }
    },
    // 添加规格
    addAttribute () {
      if (!this.attributeData.every(item => item.attributeName !== this.goodsForm.attribute)) {
        this.$message.error({
          duration: this.$store.state.duration,
          message: '请勿添加重复的规格!',
          onClose: () => {
            this.goodsForm.attribute = ''
          }
        })
        return false
      }
      if (this.attributeData.length === 3) {
        this.$message.error({
          duration: this.$store.state.duration,
          message: '规格不能超过3条!',
          onClose: () => {
            this.goodsForm.attribute = ''
          }
        })
        return false
      }
      if (this.goodsForm.attribute) {
        let addAttribute = {
          attributeName: this.goodsForm.attribute,
          sellPrice: this.sellPrice || '',
          position: this.position || ''
        }
        this.attributeData.push(addAttribute)
      } else {
        this.$message.error({
          duration: this.$store.state.duration,
          message: '请输入规格'
        })
      }
      this.goodsForm.attribute = ''
    },
    // 删除
    del (index, row) {
      row.splice(index, 1)
      this.$message({
        duration: this.$store.state.duration,
        message: '已删除',
        type: 'success'
      })
    },
    // 商品分类
    categroyList () {
      this.$http.post(this.$api + '/commodity/findAllCommodityCategory', {}).then(res => {
        if (res.responseCode === '0000') {
          this.CategoryData = res.data
        } else {
          this.$message.error({
            duration: this.$store.state.duration,
            message: res.responseMsg
          })
        }
      }).catch(() => {
        this.$message.error({
          duration: this.$store.state.duration,
          message: '请求超时！'
        })
      })
    },
    // 取消
    goback () {
      this.$router.push({
        path: '/goods/index',
        query: {
          pg: this.$route.query.pg,
          size: this.$route.query.size
        }
      })
    },
    cancel () {
      let addoredit = ''
      if (this.type === 1) {
        addoredit = '添加'
      } else {
        addoredit = '编辑'
      }
      this.$confirm('确认要放弃' + addoredit + '商品？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.push({
          path: '/goods/index',
          query: {
            pg: this.$route.query.pg,
            size: this.$route.query.size
          }
        })
        this.$message({
          duration: this.$store.state.duration,
          message: '操作成功',
          type: 'success'
        })
      }).catch(() => {
        this.$message({
          duration: this.$store.state.duration,
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 检查图片大小不超过2M
    beforeUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    // 上传商品主图
    uploadSuccess (res, file) {
      this.imgUrlList.push(res.data)
    },
    // 查看商品主图
    preView (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 删除商品主图
    removeFile (file, fileList) {
      this.imgUrlList = []
      fileList.forEach(item => {
        this.imgUrlList.push(item.url)
      })
    },
    // 上传个数超出
    overLimit () {
      this.$message.error({
        duration: this.$store.state.duration,
        message: '最多只能上传4张图片'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: auto;
}
.flex-box button {
  margin-left: 30px;
}
.el-table{
  margin-top: 15px;
}
.uploader-wrapper{
  margin: 0
}
.flex-box {
  width: 450px;
}
.el-input{
  width: 450px;
}
.el-table .el-input {
  width: 100%;
}
</style>
